//index.js
//获取应用实例
const app = getApp()

const rule = {
  lat: 31.31618, //公司位置经度
  lng: 121.39263, //公司位置纬度
  maxDistance: 2000, //最大位置偏差
  bssid: "20:6b:e7:b3:64:24" //指定BSSID
}

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    locationChecked: false, //位置信息是否已经确认
    distance: '', //当前用户距离
    wifiChecked: false, //wifi是否已经确认
    isChecked: false //最终状态
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  //按钮绑定的事件
  bindGetLocationTap: function () {
    const that = this
    wx.getLocation({
      success: function (res) {
        //判断距离
        const distance = that.getDistance(res.latitude, res.longitude)
        if (distance <= rule.maxDistance) {
          //在有效位置范围内
          that.setData({
            distance: Math.floor(distance),
            locationChecked: true
          })
          //开启wifi
          that.openWifi()
        } else {
          wx.showModal({
            title: '提醒',
            content: '当前位置已经超出允许范围',
          })
        }
      },
    })
  },
  //计算用户位置与目标位置之间的距离
  getDistance: function (lat, lng) {
    let distance = 0;
    const radLat1 = lat * Math.PI / 180;
    const radLat2 = rule.lat * Math.PI / 180;
    const deltaLat = radLat1 - radLat2;
    const deltaLng = lng * Math.PI / 180 - rule.lng * Math.PI / 180;
    distance = 2 * Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(deltaLat / 2), 2)
        +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)
      )
    );
    return distance * 6378137;
  },
  //开启wifi
  openWifi: function () {
    const that = this
    wx.startWifi({
      success: function (res) {
        that.getCurrentWifi()
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '无法开启Wifi，请开启Wifi重试',
        })
      }
    })
  },
  //获取当前连接的wifi
  getCurrentWifi: function () {
    const that = this
    wx.getConnectedWifi({
      success: function (res) {
        that.checkCurrentWifi(res.wifi)
      },
      fail: function () {
        wx.showModal({
          title: '提醒',
          content: '未连接WiFi',
        })
      }
    })
  },
  //判断当前wifi是否指定打卡wifi
  checkCurrentWifi: function (wifi) {
    if (rule.bssid === wifi.BSSID) {
      //确认验证成功
      this.setData({
        wifiChecked: true,
        isChecked: true
      })
      //还需要获取当前微信用户的OpenId，然后最终确认该用户已经完成打卡
      this.getCurrentUserOpenId()
    } else {
      wx.showModal({
        title: '提醒',
        content: '您没有连接到指定wifi，wifi验证失败',
      })
    }
  },
  //获取当前用户的OpenId
  //不安全，千万不要在实际项目中这么做
  getCurrentUserOpenId: function () {
    const appId = 'wx1b21494e77709cc2'
    const appSecret = '6859f59d69a1e4a28c860d691c4a0a1a'
    wx.login({
      success: function (res) {
        const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + appSecret + '&js_code=' + res.code + '&grant_type=authorization_code'
        wx.request({
          url: url,
          success: function (response) {
            wx.showModal({
              title: '提醒',
              content: '您的标识：' + response.data.openid + '，您已经成功打卡。',
            })
          }
        })

      }
    })

  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})
